package com.freak.wanandroid.base.dialog;


import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;

import com.freak.httpmanager.BaseViewModel;
import com.freak.httpmanager.utils.TUtil;


/**
 * BindingDialog Dialog 基类
 *
 * @author freak
 * @date 2022/09/12.
 */
public abstract class BaseDataBindingDialogFragment<T extends BaseViewModel, D extends ViewDataBinding> extends BaseDialogFragment {
    protected T mViewModel;

    protected D mDataBinding;

    /**
     * 数据绑定
     */
    protected abstract void dataObserver();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        final Window window = getDialog().getWindow();
        assert window != null;
        mDataBinding = DataBindingUtil.inflate(inflater, getLayoutId(), ((ViewGroup) window.findViewById(android.R.id.content)), false);
        mView = mDataBinding.getRoot();
        mViewModel = viewModelProviders(this, (Class<T>) TUtil.getInstance(this, 0));
        if (null != mViewModel) {
            dataObserver();
        }
        return mView;
    }

    /**
     * create ViewModelProviders
     *
     * @return ViewModel
     */
    protected <T extends ViewModel> T viewModelProviders(BaseDataBindingDialogFragment fragment, @NonNull Class<T> modelClass) {
        return new ViewModelProvider(fragment).get(modelClass);
    }
}
